package com.dituhui.tool.speech;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.log4j.Logger;

import com.alibaba.idst.nls.NlsClient;
import com.alibaba.idst.nls.NlsFuture;
import com.alibaba.idst.nls.event.NlsEvent;
import com.alibaba.idst.nls.event.NlsListener;
import com.alibaba.idst.nls.protocol.NlsRequest;
import com.alibaba.idst.nls.protocol.NlsResponse;
import com.dituhui.tool.io.Constants;

/**
 * 阿里语音转换
 * 
 * @author liweigu
 *
 */
public class AliSpeech implements NlsListener {
	private static final Logger LOGGER = Logger.getLogger(AliSpeech.class);
	private static final String APP_KEY = "nls-service";
	private static final String KEY_ID = Constants.getValue("aliKeyId");
	private static final String KEY_SECRET = Constants.getValue("aliKeySecret");;
	private NlsClient client = new NlsClient();

	/**
	 * 构造函数，初始化NlsClient。
	 */
	public AliSpeech() {
		LOGGER.info("init Nls client...");
		client.init();
	}

	/**
	 * 关闭客户端并释放资源
	 */
	public void shutDown() {
		LOGGER.info("close NLS client");
		client.close();
	}

	/**
	 * 开始转换
	 * 
	 * @param text 文本
	 * @param filePath 结果文件路径
	 */
	public void startTTS(String text, String filePath) {
		File file = new File(filePath);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		NlsRequest req = new NlsRequest();

		req.setAppKey(APP_KEY); // 设置语音文件格式
		req.setTtsRequest(text); // 传入测试文本，返回语音结果
		req.setTtsEncodeType("wav");// 返回语音数据格式，支持pcm,wav.alaw
		req.setTtsVolume(30); // 音量大小默认50，阈值0-100
		req.setTtsSpeechRate(0); // 语速，阈值-500~500
		req.setTtsBackgroundMusic(1);// 背景音乐编号
		req.setTtsVoice("xiaogang");// xiaogang代表男声，默认是女声
		req.authorize(KEY_ID, KEY_SECRET); // 请替换为用户申请到的Access Key ID和Access Key Secret
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			NlsFuture future = client.createNlsFuture(req, this); // 实例化请求,传入请求和监听器
			int total_len = 0;
			byte[] data;
			while ((data = future.read()) != null) {
				fileOutputStream.write(data, 0, data.length);
				total_len += data.length;
				LOGGER.info("tts length " + data.length);
			}
			fileOutputStream.close();
			LOGGER.info("tts audio file size is :" + total_len);
			future.await(10000); // 设置服务端结果返回的超时时间
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 消息的回调
	 * @param e NlsEvent
	 */
	@Override
	public void onMessageReceived(NlsEvent e) {
		NlsResponse response = e.getResponse();
		String result = null;
		int statusCode = response.getStatus_code();
		if (response.getTts_ret() != null) {
			result = "get tts result: statusCode=[" + statusCode + "], " + response.getTts_ret();
		}
		if (result != null) {
			LOGGER.info(result);
		} else {
			LOGGER.info(response.jsonResults);
		}
	}

	/**
	 * 识别失败的回调
	 * @param e NlsEvent
	 */
	@Override
	public void onOperationFailed(NlsEvent e) {
		LOGGER.info("on operation failed: " + e.getErrorMessage());
	}

	/**
	 * socket 连接关闭的)回调
	 * @param e NlsEvent
	 */
	@Override
	public void onChannelClosed(NlsEvent e) {
		LOGGER.info("on websocket closed.");
	}
}
